package com.ruoyi.alert.controller;

import com.ruoyi.alert.domain.Alert;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.Date;

import javax.validation.Valid;

@RestController
@RequestMapping("/alert")
public class AlertController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/send")
    public String sendAlert(@Valid @RequestBody Alert alert) {

        if (alert.getCodValueDay1() == null || alert.getCodValueDay2() == null) {
            return "COD值不能为空";
        }

        alert.setDate(new Date()); // 设置当前时间为警报时间
//        double diff = Math.abs(alert.getCodValueDay2() - alert.getCodValueDay1());
        BigDecimal diff = BigDecimal.valueOf(Math.abs(alert.getCodValueDay2() - alert.getCodValueDay1()));
        alert.setDiffValue(diff.doubleValue());
        if (diff.compareTo(BigDecimal.valueOf(500.00)) >= 0) {
            rabbitTemplate.convertAndSend("alarm.exchange", "alarm.routingkey", alert);
            return "COD差值超过阈值，警报已发送";
        }
        return "COD差值正常，无需报警";
    }
}